package com.sfang.common.base.http.Interceptor;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.sfang.common.base.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 手动添加分布式跟踪ID
 *
 * @author xuzilou
 * @date 2021/3/24 16:20
 */
@Slf4j
@Component
public class LogMdcInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String traceId = request.getHeader(Constants.TRACK_ID);
        MDC.put(Constants.TRACK_ID, StrUtil.isBlank(traceId) ? IdUtil.simpleUUID() : traceId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        response.setHeader(Constants.TRACK_ID, MDC.get(Constants.TRACK_ID));
        MDC.clear();
    }

}
